﻿using System;
using System.Collections.Generic;


namespace csMake3D.core {
public class InterpolatedArray<T> {       
        public  delegate T interpolator(T a, T b, float x);       


        private interpolator m_interpolator = null;
        private List<T>vertices = new List<T>(10);
        private int out_points;

        public InterpolatedArray(int interpolated_points, interpolator intp) {            
            out_points = interpolated_points;
            m_interpolator = intp;
        }

        public InterpolatedArray(int interpolated_points, interpolator intp, List<T> list)
            : this(interpolated_points, intp) {
            vertices = list;
        }


        public T this[int index] {
            get {

                if (vertices.Count == 0) throw new Exception();
                else if (vertices.Count == 1) return vertices[0];



                float x = (float)index / (float)out_points;
                x *= vertices.Count;

                int idx = (int)Math.Floor(x);
                x = x - (float)idx;
                int idx1 = idx + 1;

                if (idx1 >= vertices.Count) {
                    return vertices[idx];
                }
                else if (idx1 < 0) {
                    return vertices[0];
                }
                T ret = m_interpolator(vertices[idx], (T)vertices[idx1], x);

                return ret;
            }
            set {
                //List[index] = value;
            }
        }

        public int Count { get { return out_points; } set { out_points = value; } }

        public void AddControlPoint(T value) {
             vertices.Add(value);
        }
        
        public void RemoveControlPoint(int idx) {
             vertices.RemoveAt(idx);
        }

        public T GetControlPoint(int idx) {
            return vertices[idx];
        }

        public int ControlPointsCount { get { return vertices.Count; } }

        public void Clear() {
            vertices.Clear();
        }


        public List<T> getInterpolatedList() {

            List<T> ret = new List<T>(this.out_points);
            for (int i = 0; i < out_points; i++)
                ret.Add(this[i]);
            return ret;
        }


    }
    }

